/**
 * 格式化散点图
 * @des {
 *   仅格式化组件所需要的数据
 * }
 */
import { $each  } from '../index';
import { isNullOrEmpty } from '../is';
import { handleConditionExtend } from '../conditionFormat/useConditionFormat.js';
import { processXAis } from './lineAndBarFormat.js';
/**
 * 格式化series
 * */
function processSeriesDataScatter(datasets, option = {}) {
  const seriesData = [];
  const { source, fieldNameChainMap, conditionData, conditionOptions } = datasets;
  const { yAxis, legend, xAxis, xAxisScatter, xData } = option;
  if (!yAxis) {
    return [];
  }
  let yAxisArr = [];
  let xAxisArr = [];
  let xAxisScatterArr = [];
  // 判断是否是多维度
  if (xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = [xAxis];
  }
  // 判断X轴度量
  if (xAxisScatter.includes('&')) {
    xAxisScatterArr = xAxisScatter.split('&');
  } else {
    xAxisScatterArr = [xAxisScatter];
  }
  // 判断是否是多度量
  if (yAxis.includes('&')) {
    yAxisArr = yAxis.split('&');
  } else {
    yAxisArr = [yAxis];
  }
  // 不存在颜色维度,就不需要分组
  if (!legend) {
    yAxisArr.forEach((yItem) => {
      const yData = [];
      source.forEach((dataItem) => {
        const value = [...xAxisScatterArr, yItem, ...xAxisArr].map((item) => {
          // 根据原始字段名称收集数据
          if (fieldNameChainMap.xAxisScatter && fieldNameChainMap.xAxisScatter[item]) {
            conditionData[fieldNameChainMap.xAxisScatter[item]].push({ value: dataItem[item] });
          }
          if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[item]) {
            conditionData[fieldNameChainMap.yAxis[item]].push({ value: dataItem[item] });
          }
          return dataItem[item];
        });
        yData.push({ value });
      });
      seriesData.push({
        name: yItem,
        dataFormatType: 'yAxis',
        data: yData,
      })
    });
    // 条件格式处理
    const options = {
      conditionData,
      isExistLegend: false, // 是否存在颜色维度
      seriesData,
      legendFieldName: null,
      fieldNameChainMap,
      chartTag: 'scatter',
    };
    handleConditionExtend(options, conditionOptions);
    return seriesData;
  }
  const legendMap = source.reduce((acc, current) => {
    let name = '';
    let num = '';
    xAxisScatterArr.forEach((xItem) => {
      num += `-${current[xItem]}`;
    });
    xAxisArr.forEach((xItem) => {
      name += `-${current[xItem]}`;
    });
    if (acc[current[legend]]) {
      acc[current[legend]].push([
        Number(num.substring(1)),
        current[yAxisArr[0]],
        name.substring(1),
      ]);
    } else {
      acc[current[legend]] = [[Number(num.substring(1)), current[yAxisArr[0]], name.substring(1)]];
    }
    return acc;
  }, {});
  /**
   * yAxis
   * [
   *  { name: '天工傲', data: [1, 0, 0, 2] },
   *  { name: '事件网', data: [3, 2, 0, 0] }
   * ]
   */
  $each(legendMap, (list, name) => {
    let result = {};
    const data = [];
    xData.forEach((xItem) => {
      // 遍历list数组中每一项的name值与xData数组中的每一项的value值进行查找
      result = list.find((item) => item[2] === xItem.value) || [];
      data.push({
        value: result,
      });
      if (fieldNameChainMap.xAxisScatter && fieldNameChainMap.xAxisScatter[xAxisScatter]) {
        conditionData[fieldNameChainMap.xAxisScatter[xAxisScatter]].push({ value: result[0] });
      }
      if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[yAxis]) {
        conditionData[fieldNameChainMap.yAxis[yAxis]].push({value: result[1]});
      }
    });
    if (name) {
      seriesData.push({
        name,
        data,
        dataFormatType: 'yAxis',
      });
      // 根据原始字段名称收集颜色维度数据
      fieldNameChainMap?.legend[legend] &&
        conditionData[fieldNameChainMap?.legend[legend]].push({ value: name });
    }
  });
  // 条件格式处理
  const options = {
    conditionData,
    isExistLegend: true, // 是否存在颜色维度
    seriesData,
    legendFieldName: fieldNameChainMap['legend'][legend],
    fieldNameChainMap,
    chartTag: 'scatter',
  };
  handleConditionExtend(options, conditionOptions);
  return seriesData;
}

/**
 * 格式化气泡图series
 * */
function processSeriesDataBubble(datasets, option = {}) {
  const seriesData = [];
  const { source, fieldNameChainMap, conditionData, conditionOptions } = datasets;
  const { yAxis, xAxis, xAxisScatter, yAxisSize } = option;
  if (!yAxis) {
    return [];
  }
  let yAxisArr = [];
  let xAxisArr = [];
  let xAxisScatterArr = [];
  let yAxisSizeArr = [];
  // 判断是否是多维度
  if (xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = [xAxis];
  }
  // 判断X轴度量
  if (xAxisScatter.includes('&')) {
    xAxisScatterArr = xAxisScatter.split('&');
  } else {
    xAxisScatterArr = [xAxisScatter];
  }
  // 判断是否是多度量
  if (yAxis.includes('&')) {
    yAxisArr = yAxis.split('&');
  } else {
    yAxisArr = [yAxis];
  }
  // 判断是否是多气泡大小/度量
  if (yAxisSize.includes('&')) {
    yAxisSizeArr = yAxisSize.split('&');
  } else {
    yAxisSizeArr = [yAxisSize];
  }
  yAxisArr.forEach((yItem) => {
    const yData = [];
    source.forEach((dataItem) => {
      const value = [...xAxisScatterArr, yItem, ...yAxisSizeArr, ...xAxisArr].map((item) => {
        // 根据原始字段名称收集数据
        if (fieldNameChainMap.xAxisScatter && fieldNameChainMap.xAxisScatter[item]) {
          conditionData[fieldNameChainMap.xAxisScatter[item]].push({ value: dataItem[item] });
        }
        if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[item]) {
          conditionData[fieldNameChainMap.yAxis[item]].push({ value: dataItem[item] });
        }
        return dataItem[item];
      });
      // 气泡大小为空时，不显示气泡
      if (value && value.length && value[2] !== null) {
        yData.push({ value });
      }
    });
    seriesData.push({
      name: yAxisSize,
      dataFormatType: 'yAxis',
      data: yData,
    })
  });
  // 条件格式处理
  const options = {
    conditionData,
    isExistLegend: false, // 是否存在颜色维度
    seriesData,
    legendFieldName: null,
    fieldNameChainMap,
    chartTag: 'scatter',
  };
  handleConditionExtend(options, conditionOptions);
  return seriesData;
}

/**
* 格式化打卡气泡图series
* */
function processScatterPunchSeriesData(datasets, option = {}) {
  const seriesData = [];
  const { source, fieldNameChainMap, conditionData, conditionOptions ,type } = datasets;
  const { yAxis, xAxis, yAxisSize, xData, yAxisData } = option;
  if (!yAxis) {
    return [];
  }
  let yAxisArr = [];
  let xAxisArr = [];
  let yAxisSizeArr = [yAxisSize];
  // 判断是否是多维度
  if (xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = [xAxis];
  }
  // 判断是否是多度量
  if (yAxis.includes('&')) {
    yAxisArr = yAxis.split('&');
  } else {
    yAxisArr = [yAxis];
  }
  yAxisArr.forEach((yItem) => {
    const yData = [];
    source.forEach((dataItem,index) => {
      [ yItem, ...xAxisArr, ...yAxisSizeArr].map((item) => {
        // 根据原始字段名称收集数据
        if (fieldNameChainMap.xAxisScatter && fieldNameChainMap.xAxisScatter[item]) {
          conditionData[fieldNameChainMap.xAxisScatter[item]].push({ value: dataItem[item] });
        }
        if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[item]) {
          conditionData[fieldNameChainMap.yAxis[item]].push({ value: dataItem[item] });
        }
      });
      if (yAxisArr.length && !isNullOrEmpty(dataItem[yAxisSizeArr])) {
        const xAxisName = type === 'STATIC' ? dataItem[xAxis] : xData[index].value;
        yData.push({value: [dataItem[yItem],xAxisName, dataItem[yAxisSizeArr], xAxisName]});
      }
    });
    // 处理X轴对应的index值
    xData.forEach((xItem,xIndex) => {
      yData.forEach(item => {
        if(item.value[1] === xItem.value) {
          item.value[1] = xIndex;
        }
      })
    })
    // 处理y轴对应的index值
    for(let i = 0, len= yData.length; i < len; i++) {
      for(let j = 0, lens= yAxisData.length; j < lens; j++) {
        if(yData[i].value[0] === yAxisData[j]) {
          yData[i].value[0] = j;
          break;
        }
      }
    }
    seriesData.push({
      name: yItem,
      dataFormatType: 'yAxisSize',
      data: yData,
    })
  });
  // 条件格式处理
  const options = {
    conditionData,
    isExistLegend: false, // 是否存在颜色维度
    seriesData,
    legendFieldName: null,
    fieldNameChainMap,
    chartTag: 'scatter',
  };
  handleConditionExtend(options, conditionOptions);
  return seriesData;
}

/**
 * 散点图格式化
 */
export function scatterFormat(datasets) {
  const { yAxis, legend, xAxis, xAxisScatter } = datasets.dimensions;
  const xAxisData = processXAis(datasets);
  const option = {
    xData: xAxisData,
    yAxis,
    legend,
    xAxis,
    xAxisScatter,
  };
  const seriesData = processSeriesDataScatter(datasets, option);
  return {
    seriesData,
  };
}

/**
 * 气泡图格式化
 */
export function scatterBasicFormat(datasets) {
  const { yAxis, legend, xAxis, xAxisScatter, yAxisSize } = datasets.dimensions;
  const xAxisData = processXAis(datasets);
  const option = {
    yAxis,
    legend,
    xAxis,
    xAxisScatter,
    yAxisSize,
  };
  const seriesData = processSeriesDataBubble(datasets, option);
  return {
    seriesData,
  };
}

/**
 * 打卡-气泡图格式化
 */
export function scatterPunchFormat(datasets) {
  const { yAxis, legend, xAxis, yAxisSize } = datasets.dimensions;
  const xData = processXAis(datasets);
  const yAxisValue = [];
  const yMap = {};
  datasets.source.forEach(item =>{
    if (!yMap[item[yAxis]]) {
      yAxisValue.push(item[yAxis])
      yMap[item[yAxis]] = true;
    }
  });
  const option = {
    xData,
    yAxisData: yAxisValue,
    yAxis,
    legend,
    xAxis,
    yAxisSize,
  };
  const seriesData = processScatterPunchSeriesData(datasets, option);
  return {
    seriesData,
    xAxisData: yAxisValue,
    yAxisData: xData,
  };
}
